package com.xiaoh.compare.utils;

import com.xiaoh.compare.bo.CompareMo;
import difflib.DiffRow;
import difflib.DiffRowGenerator;
import net.htmlparser.jericho.Source;

import java.io.*;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

//被注释的地方先不要删，可能会有用！
public class CompareString {
//	变化的结果（tag）
	public static final String Result_EQUAL = "EQUAL";
	public static final String Result_INSERT = "INSERT";
	public static final String Result_DELETE = "DELETE";
	public static final String Result_CHANGE = "CHANGE";
	/***
	 * 读文件
	 * @param filename
	 * @return
	 */
	private static List<String> fileToLines(String filename) {
		List<String> lines = new LinkedList<String>();
		String line = "";
		try {
			  //编译环境为GBK的情况
	         BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(filename), "GBK"));          
//			BufferedReader in = new BufferedReader(new FileReader(filename));
			while ((line = in.readLine()) != null) {
				lines.add(line);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return lines;
	}
	
	/***
	 * 对文件进行比较
	 * INSERT, DELETE, CHANGE, EQUAL
	 * @param fromFileName 原来的文件名
	 * @param toFileName 新的文件名
	 */
	public static List<CompareMo> compareAll(String fromFileName, String toFileName) {
		List<String> original = fileToLines(fromFileName);
		List<String> revised = fileToLines(toFileName);

		final DiffRowGenerator.Builder builder = new DiffRowGenerator.Builder();
		final DiffRowGenerator dfg = builder.build();
		final List<DiffRow> rows = dfg.generateDiffRows(original, revised);
		List<CompareMo> listCompareMo = new ArrayList<CompareMo>();
		int i=1;
		int oldSize = original.size();
		int newSize = revised.size();
		int insertSize = 0;
		int deleteSize = 0;
		for (final DiffRow diffRow : rows) {
			String tag = diffRow.getTag().toString();
			String oldLine = diffRow.getOldLine();
			String newLine = diffRow.getNewLine();
			if(Result_CHANGE.equals(tag)){
				boolean isInset = false;
				if ((i-insertSize) <= oldSize) {
					if(oldLine!=null&& oldLine.trim().length()==0){
						if(!original.get(i-1-insertSize).equals(oldLine)){
							tag = Result_INSERT;
							isInset = true;
							insertSize ++;
						}
					}
				}
				if (!isInset) {
					if ((i-deleteSize) <= newSize) {
						if(newLine!=null&& newLine.trim().length()==0){
							if(!revised.get(i-1-deleteSize).equals(oldLine)){
								tag = Result_DELETE;
								isInset = true;
								deleteSize ++;
							}
						}
					}
				}
			}
					
//			listCompareMo.add(new CompareMo(
//					i, oldLine, 
//					newLine, 
//					tag
//			));
//			i++;
			listCompareMo.add(new CompareMo(
					 oldLine, 
					newLine, 
					tag
			));						
		}
		return listCompareMo;
	}
	
//	去除html的所有标签
	public static String getPlainTextWithoutHtmlTag(String  content) {
        if(content == null || "".equals(content)){
            return "";
        }else{
            Source src = new Source(content);
            String str = src.getTextExtractor().toString().trim();
            return str.replaceAll(" ","").replaceAll("　　", "");
        }
    }

	
	 
	
//	main方法
//	public static void main(String[] args) throws IOException {
	
	
	//调用此方法即可
	//字符串比较方法
	
	public static String getcompareString(String  contentWord4,String  contentWord5,String  contentWord6) throws IOException {
		
		String a="";
		String contentWord="";
		int count=0;
		String b2="";
		String b3="";		

//	将要比较的String字符串放到一个文件中(第一串字符处理)	
//		 contentWord4="我"+"\n"+"你";
		File doc4=new File("C:\\compareSring\\newFile4.doc");	
        File file = new File("C:\\compareSring");
		if(!file.exists()){
			file.mkdirs();
		if(!doc4.exists()){
			try {
				doc4.createNewFile();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
//		byte doc4bytes[]=new byte[512];
//		doc4bytes=contentWord4.getBytes(); 
//		int doc4b=contentWord4.length();  
//		FileOutputStream doc4fos=new FileOutputStream(doc4);
//		doc4fos.write(doc4bytes,0,doc4b);
//		doc4fos.close();
		
		
//		或		
		FileOutputStream writerStream = new FileOutputStream(doc4);
		  //编译环境为UTF8的情况下设置为UTF8
//		BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(writerStream, "UTF-8"));
		  //编译环境为GBK的情况下设置为GBK
		BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(writerStream, "GBK"));
		try {
			writer.write(contentWord4);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			writer.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
				
			
	
//		将要比较的String字符串放到一个文件中(第二串字符处理)	
//		 contentWord5="我了"+"\n"+"你了";
			
		File doc5=new File("C:\\compareSring\\newFile5.doc");	
        File file2 = new File("C:\\compareSring");
		if(!file2.exists()){
			file2.mkdirs();
		if(!doc5.exists()){
			doc5.createNewFile();
		}
	}
//		byte doc5bytes[]=new byte[512];
//		doc5bytes=contentWord5.getBytes(); 
//		int doc5b=contentWord5.length();  
//		FileOutputStream doc5fos=new FileOutputStream(doc5);
//		doc5fos.write(doc5bytes,0,doc5b);
//		doc5fos.close();
		
//		或	
		FileOutputStream writerStream5 = new FileOutputStream(doc5);
		//编译环境为GBK的情况
		BufferedWriter writer5 = new BufferedWriter(new OutputStreamWriter(writerStream5, "GBK"));
		writer5.write(contentWord5);
		writer5.close(); 

         
//		将要比较的String字符串放到一个文件中(第三串字符处理)	
//		 contentWord6="你了"+"\n"+"他了";
		File doc6=new File("C:\\compareSring\\newFile6.doc");	
        File file3 = new File("C:\\compareSring");
		if(!file3.exists()){
			file3.mkdirs();
		if(!doc6.exists()){
			doc6.createNewFile();		
		     }
		}
//		byte doc6bytes[]=new byte[512];
//		doc6bytes=contentWord6.getBytes(); 
//		int doc6b=contentWord6.length();  
//		FileOutputStream doc6fos=new FileOutputStream(doc6);
//		doc6fos.write(doc6bytes,0,doc6b);
//		doc6fos.close();   
		
//		或		
		FileOutputStream writerStream6 = new FileOutputStream(doc6);
		  //编译环境为GBK的情况
		BufferedWriter writer6 = new BufferedWriter(new OutputStreamWriter(writerStream6, "GBK"));
		writer6.write(contentWord6);
		writer6.close(); 
					
		
		
//比较差异
		List<CompareMo> compares = CompareString.compareAll(
//				"C:\\compareText\\originalFile.txt",
//				"C:\\compareText\\newFile.txt");
				
				"C:\\compareSring\\newFile4.doc",
				"C:\\compareSring\\newFile5.doc");

		for (CompareMo compare : compares) {
//			System.out.println("66"+compare.getId() + " 结果 :" + compare.getType()
//					+ ":" + compare.getOldText() + "<>" + compare.getNewText());
			
			if(compare.getType()=="CHANGE") {	
				 a=compare.getNewText();				
				 contentWord=	getPlainTextWithoutHtmlTag(a);
			System.out.println(contentWord);			
		
//计算有差异的行数		
			count=++count;
			}		
		}
		
		
			
//				File doc=new File("C:\\compareText\\newFile3.doc");
//				System.out.println("666"+contentWord);
//				if(!doc.exists()){
//					doc.createNewFile();
//				}
//				byte bytes[]=new byte[512];
//				bytes=contentWord.getBytes(); 
//				int b=contentWord.length(); 		         
//				FileOutputStream fos=new FileOutputStream(doc);
//				fos.write(bytes,0,b);
//				fos.close();
		
    //比较差异
		
		List<CompareMo> compares2 = CompareString.compareAll(
//				"C:\\compareText\\newFile.txt",
//				"C:\\compareText\\newFile2.txt");					
				
		
				"C:\\compareSring\\newFile5.doc",
	         	"C:\\compareSring\\newFile6.doc");

		for (CompareMo compare : compares2) {
//			System.out.println("555"+compare.getId() + " 结果 :" + compare.getType()
//					+ ":" + compare.getOldText() + "<>" + compare.getNewText());
			
//			if(compare.getType()!="DELETE"&&compare.getType()!="CHANGE") {
//			if(compare.getType()=="CHANGE") {
			if(compare.getType()=="INSERT"||compare.getType()=="EQUAL"&&count<2) {

//				System.out.println( "最新版本（拼接完成）"+a);			
				 b2=getPlainTextWithoutHtmlTag(compare.getNewText());
			    System.out.println(b2);
			}
					
			else	if(compare.getType()=="CHANGE"&&count==0) {
//				System.out.println( "最新版本（拼接完成）"+a);				
				 b3=getPlainTextWithoutHtmlTag(compare.getOldText());
				 b2=getPlainTextWithoutHtmlTag(compare.getNewText());
			    System.out.println(b3);
			    System.out.println(b2);
			  
			}		
		}
		
		//用来判断应该返回哪个值
		
		if(b3!=null) {
		return contentWord+"\n"+b3+"\n"+b2;		
		}else {			
			return contentWord+"\n"+b2;	
			
		}
	}
}

